find_program(WAYLANDSCANNER_EXECUTABLE NAMES wayland-scanner)
find_program(UKUIWAYLANDSCANNER_EXECUTABLE NAMES ukuiwaylandscanner)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(UkuiWaylandClient
    REQUIRED_VARS WAYLANDSCANNER_EXECUTABLE  WAYLANDSCANNER_EXECUTABLE
)
if (NOT UkuiWaylandClient_FOUND)
    message(FATAL_ERROR "UkuiWaylandScanner not found. Please install ukuiwaylandscanner.")
endif()

function(ukui_add_wayland_client_protocol out_var)
    # Parse arguments
    set(oneValueArgs PROTOCOL)
    cmake_parse_arguments(ARGS "" "${oneValueArgs}" "" ${ARGN})

    get_filename_component(_infile ${ARGS_PROTOCOL} ABSOLUTE)
    get_filename_component(_base_name ${_infile} NAME_WE)

    set(_header "${CMAKE_CURRENT_BINARY_DIR}/${_base_name}.h")
    set(_code "${CMAKE_CURRENT_BINARY_DIR}/${_base_name}.cpp")
    set(_wayland_client_header "${CMAKE_CURRENT_BINARY_DIR}/wayland-${_base_name}-client-protocol.h")
    set(_wayland_code "${CMAKE_CURRENT_BINARY_DIR}/wayland-${_base_name}-protocol.c")

    set_source_files_properties(${_header} ${_code} ${_wayland_client_header} ${_wayland_code} GENERATED)
    set_property(SOURCE ${_header} ${_code} ${_wayland_client_header} ${_wayland_code} PROPERTY SKIP_AUTOMOC ON)

    add_custom_command(OUTPUT "${_header}" "${_wayland_client_header}" "${_wayland_code}" "${_code}"
        COMMAND ${UKUIWAYLANDSCANNER_EXECUTABLE} ${_infile} ${CMAKE_CURRENT_BINARY_DIR}
        DEPENDS ${_infile} VERBATIM)


    if (TARGET ${out_var})
        target_sources(${target_or_sources_var} ${_wayland_code} ${_code})
    else()
        list(APPEND ${out_var} ${_wayland_code} ${_code})
        set(${out_var} ${${out_var}} PARENT_SCOPE)
    endif()

    set(${out_var} ${${out_var}} PARENT_SCOPE)
endfunction()

include("${CMAKE_CURRENT_LIST_DIR}/UkuiWaylandClientTargets.cmake")
include_directories(${CMAKE_CURRENT_BINARY_DIR})
